package world.criver.imagecompresstool.function;

import org.apache.commons.imaging.ImageFormats;
import org.apache.commons.imaging.Imaging;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.ArrayList;

public class funIcon {
    public static final String mode_auto="ico1";
    public static final String mode_16x16="ico2";
    public static final String mode_32x32="ico3";
    public static final String mode_48x48="ico4";
    public static final String mode_64x64="ico5";
    public static final String mode_128x128="ico6";
    public static final String mode_256x256="ico7";

    /**
     * 转icon
     * @param o
     * @param mode
     * @return list<[old_name,old_size,result,new_name,new_size]>
     */
    public ArrayList<String[]> toIcon(File o, String mode){
        try {
            ArrayList<String[]> re=new ArrayList<>();
            String nm = o.getName().substring(0, o.getName().lastIndexOf("."));
            BufferedImage oi = ImageIO.read(o);
            switch (mode){
                case mode_16x16 -> re.add(getResult(o,oi,nm,16));
                case mode_32x32 -> re.add(getResult(o,oi,nm,32));
                case mode_48x48 -> re.add(getResult(o,oi,nm,48));
                case mode_64x64 -> re.add(getResult(o,oi,nm,64));
                case mode_128x128 -> re.add(getResult(o,oi,nm,128));
                case mode_256x256 -> re.add(getResult(o,oi,nm,256));
                default -> {
                    if(oi.getWidth()>=16 && oi.getHeight()>=16)re.add(getResult(o,oi,nm,16));
                    if(oi.getWidth()>=32 && oi.getHeight()>=32)re.add(getResult(o,oi,nm,32));
                    if(oi.getWidth()>=48 && oi.getHeight()>=48)re.add(getResult(o,oi,nm,48));
                    if(oi.getWidth()>=64 && oi.getHeight()>=64)re.add(getResult(o,oi,nm,64));
                    if(oi.getWidth()>=128 && oi.getHeight()>=128)re.add(getResult(o,oi,nm,128));
                    if(oi.getWidth()>=256 && oi.getHeight()>=256)re.add(getResult(o,oi,nm,256));
                }
            }
            return re;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
    private String[] getResult(File o,BufferedImage oi,String nm,int size){
        nm=nm+"_"+size+"x"+size+".ico";
        File np=new File(o.getParent()+"/"+nm);
        boolean r=writeIcon(oi,np,size);
        return new String[]{o.getName(),o.length()+"",r+"",nm,(r? nm.length() : 0)+""};
    }
    private boolean writeIcon(BufferedImage o,File np,int size){
        try {
            BufferedImage n = new BufferedImage(size, size, BufferedImage.TYPE_4BYTE_ABGR);
            Graphics g = n.getGraphics();
            g.drawImage(o, 0, 0, size, size, null);
            Imaging.writeImage(n, np, ImageFormats.ICO);
            return true;
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }
    }
}
